﻿using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using JTTD.Common.Attribute;
using JTTD.Domain;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.CompanyUserInfo.Response;
using JTTD.Domain.Dtos.UserInfo;
using JTTD.Domain.Dtos.UserInfo.Request;
using JTTD.Domain.Dtos.UserInfo.Response;
using JTTD.Domain.Dtos.WeiXin;
using JTTD.Domain.IService;
using Newtonsoft.Json;
using JTTD.Error;
using JTTD.Extensions;
using Microsoft.AspNetCore.Mvc;

namespace JTTD.Controllers
{
    /// <summary>
    /// 用户接口
    /// </summary>
    [Route("api/user")]
    [ApiController]
    public class UserController : BaseController
    {
        private readonly IUserInfoService _userInfoService;

        private readonly IWeiXinService _weiXinService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userInfoService"></param>
        /// <param name="weiXinService"></param>
        public UserController(IUserInfoService userInfoService, IWeiXinService weiXinService)
        {
            _userInfoService = userInfoService;
            _weiXinService = weiXinService;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("register")]
        [UnAuthorize]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<int>))]
        public async Task<IActionResult> UserRegister([FromBody] UserRegisterRequestDto model)
        {
            var data = await _userInfoService.UserRegister(model);
            return Ok(data);
        }

        /// <summary>
        /// 用户手机注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("registerByPhone")]
        [UnAuthorize]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<int>))]
        public async Task<IActionResult> UserRegisterByPhone([FromBody] UserRegisterRequestDto model)
        {
            var data = await _userInfoService.UserRegisterByPhone(model);
            return Ok(data);
        }


        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("update")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> UpdateUser([FromBody] UpdateUserRequestDto model)
        {
            var data = await _userInfoService.UpdateUser(UserId, model);
            return Ok(data);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("search")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<UserInfoResponseDto>))]
        public async Task<IActionResult> SearchUserInfo([FromBody] SearchUserInfoRequestDto model)
        {
            var data = await _userInfoService.SearchUserInfo(model);
            return Ok(data);
        }


        /// <summary>
        /// 获取用户信息(H5前端)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("getUserInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<UserInfoResponseDto>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> GetUserInfo()
        {
            SearchUserInfoRequestDto model = new SearchUserInfoRequestDto { Id = UserId };
            var user = await _userInfoService.SearchUserInfo(model);
            return Ok(user);
        }

        /// <summary>
        /// 分页查询用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("searchPage")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<PageResult<UserInfoResponseDto>>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> SearchUserInfoPage(SearchUserInfoPageRequestDto model)
        {
            return Ok(await _userInfoService.SearchUserInfoPage(model));
        }


        /// <summary>
        /// 获取微信用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("getWeiXinUserInfo")]
        [UnAuthorize]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<WXOAuthUserInfo>))]
        public async Task<IActionResult> GetWeiXinUserInfo(string code, int userType)
        {
            var tokenResult = await _weiXinService.GetAccessToken(code);
            if (tokenResult.IsSuccess)
            {
                var user = await _weiXinService.GetWXOAuthUserInfo(tokenResult.Data.access_token, tokenResult.Data.openid);
                if (user.IsSuccess)
                {
                    SearchUserInfoRequestDto search = new SearchUserInfoRequestDto();
                    search.WxOpenId = user.Data.openid;
                    LogHelper.WriteLog(JsonConvert.SerializeObject(user.Data));
                    var item = await _userInfoService.SearchUserInfo(search);
                    if (item.Data == null)
                    {
                        UserRegisterRequestDto userRegister = new UserRegisterRequestDto();
                        userRegister.Birthday = null;
                        userRegister.Gender = user.Data.sex;
                        userRegister.WxOpenId = user.Data.openid;
                        userRegister.UserName = user.Data.nickname;
                        userRegister.HeadUrl = user.Data.headimgurl;
                        await _userInfoService.UserRegister(userRegister);
                    }
                }
                return Ok(user);
            }
            else
            {
                return Ok(tokenResult);
            }
        }


        //[HttpPost]
        //[Route("TestGetInfo")]
        //[UnAuthorize]
        //[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<List<WXOAuthUserInfo>>))]
        //public async Task<IActionResult> TestGetInfo(WXOAuthUserInfo user)
        //{
        //    SearchUserInfoRequestDto search = new SearchUserInfoRequestDto();
        //    search.WxOpenId = user.openid;
        //    var item = await _userInfoService.SearchUserInfo(search);
        //    if (item.Data == null)
        //    {
        //        UserRegisterRequestDto userRegister = new UserRegisterRequestDto();
        //        userRegister.Birthday = null;
        //        userRegister.Gender = user.sex;
        //        userRegister.WxOpenId = user.openid;
        //        userRegister.UserName = user.nickname;
        //        await _userInfoService.UserRegister(userRegister);
        //    }
        //    return Ok(user);
        //}


        /// <summary>
        /// 微信公众号修改用户密码（h5）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        //[HttpPut]
        //[Route("modifyUserPassword")]
        //[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        //[UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        //public async Task<IActionResult> ModifyUserPassword([FromBody]UpdateUserPwdRequestDto dto)
        //{
        //    var result = await _userInfoService.ModifyUserPassword(UserId, dto);
        //    return Ok(result);
        //}

        ///// <summary>
        ///// 重置用户密码（后台）
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <returns></returns>
        //[HttpPut]
        //[Route("resetUserPassword/{userId}")]
        //[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        //[UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        //public async Task<IActionResult> ResetUserPassword([FromRoute]int userId)
        //{
        //    var result = await _userInfoService.ResetUserPassword(userId);
        //    return Ok(result);
        //}

        /// <summary>
        /// 用户关注店家（h5）
        /// </summary>
        /// <param name="shopId">店家id</param>
        /// <returns></returns>
        [HttpPost]
        [Route("attentionShops/{shopId}")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> AttentionShop([FromRoute] int shopId)
        {
            var result = await _userInfoService.AttentionShop(shopId, UserId);
            return Ok(result);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("DeleteUserInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Admin)]
        public async Task<IActionResult> DeleteUserInfo(int userId)
        {
            var result = await _userInfoService.DeleteUserInfo(userId);
            return Ok(result);
        }

        /// <summary>
        /// 用户取消关注店家（h5）
        /// </summary>
        /// <param name="shopId">店家id</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("attentionShops/{shopId}")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<bool>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> CancelAttentionShop([FromRoute]int shopId)
        {
            var result = await _userInfoService.CancelAttentionShop(shopId, UserId);
            return Ok(result);
        }

        /// <summary>
        /// 用户查询自己关注的店家（h5）
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getUserAttentionShops")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<PageResult<GetShopUserDto>>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> GetUserAttentionShops(BaseSearch search)
        {

            var result = await _userInfoService.GetUserAttentionShops(UserId, search);
            return Ok(result);
        }

        /// <summary>
        /// 检查用户信息 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckUserInfo")]
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ApiResult<PageResult<bool>>))]
        [UserRoot(UserType = Common.Enum.UserTypeEnum.Ordinary)]
        public async Task<IActionResult> CheckUserInfo()
        {
            return Ok(await _userInfoService.CheckUserInfo(UserId));
        }
    }
}